
(function () {
    /*
  * 页面公共参数
  */
    var o = {
        dataName: 'user',
        fileSize: 600,
        inputData: {}
    };

    /*
     * 给页面参数赋值
     */
    function setParam() {
        var result = $.extend(true, o, getUrlParamsToJson());

        return result;
    }

    function initPage() {
        clearData();
        getCodeClick();

        $('#btn_submit').on('click', function () {
            submit();
        });

        isSupportAndUploadImg('#file_p1,#file_p2', function () {
            uploadControl('#file_p1', '#img_p1', '#p1');
            uploadControl('#file_p2', '#img_p2', '#p2');
        });

        setData();
        inputDataSaveEvent(o);
    }

    /**
     * 清除该页面保存的数据
     * author:陈偲
     * time:20180403
     */
    function clearData() {
        if (o.clear)
            saveJsonData().clearAppointLocalStorage([o.dataName]);
    }

    /**
     * 设置保存的数据
     * author:陈偲
     * time:20170811
     * 
     */
    function setData() {
        if (saveJsonData().isExists(o.dataName)) {
            o.inputData = saveJsonData().getData(o.dataName, 1);
            // debugger;
            for (var key in o.inputData) {
                var item = o.inputData[key];

                var $visibleObjs = $('#frm');
                var $hiddens = $('#token');

                $visibleObjs = $.merge($visibleObjs, $hiddens);

                if (item.type === 'text' || item.type === 'number' || item.type === 'tel') {
                    $visibleObjs.find('input[name="' + key + '"]').val(item.value);
                } else if (item.type === 'select') {
                    $(key).val(item.value);
                } else if (item.type === 'cs_checkbox') {
                    $visibleObjs.find('span[cs-name="checkbox"]').eq(item.value).click();
                } else if (item.type === 'checkbox') {
                    $(key).attr('checked', item.value);
                } else if (item.type === 'hidden') {
                    $visibleObjs.filter(tempKey).val(item.value);
                    $('#file_' + tempKey.substring(1)).siblings().attr('src', item.value);
                    $('input[name="file_' + tempKey.substring(1) + '"]:visible').siblings('img').attr('src', item.value);
                }


                // console.log(key + ':' + o.inputData[key]);
            }
        }
    }

    // /**
    //  * 设置保存的数据
    //  * author:陈偲
    //  * time:20170811
    //  * 
    //  */
    // function setData() {
    //     if (saveJsonData().isExists(o.dataName)) {
    //         o.inputData = saveJsonData().getData(o.dataName, 1);
    //         // debugger;
    //         for (var key in o.inputData) {
    //             var item = o.inputData[key];

    //             var $visibleObjs = $('#frm');

    //             for (var tempKey in o.inputData[item]) {
    //                 var val = o.inputData[item][tempKey];

    //                 if (val.type === 'text' || val.type === 'number' || val.type === 'tel') {
    //                     $visibleObjs.find('input[name="' + tempKey + '"]').val(val.value);
    //                 } else if (val.type === 'checkbox') {
    //                     $visibleObjs.find(tempKey).attr('checked', val.value);
    //                 } else if (val.type === 'hidden') {
    //                     $visibleObjs.filter(tempKey).val(val.value);
    //                     $('#file_' + tempKey.substring(1)).siblings().attr('src', val.value);
    //                     $('input[name="file_' + tempKey.substring(1) + '"]:visible').siblings('img').attr('src', val.value);
    //                 } else if (val.type === 'select') {
    //                     $(tempKey).val(val.value);
    //                 }
    //             }


    //         // console.log(key + ':' + o.inputData[key]);
    //         }
    //     }
    // }

    /**
     * 是否支持上传图片
     * @param {*} fileObj 
     * author:陈偲
     * time:20180402
     * 
     */
    function isSupportAndUploadImg(fileObj, func) {
        if (typeof (FileReader) === 'undefined') {
            Common.toast("不支持的上传图片", 5000);
            $(fileObj).attr('disabled', true);
        } else {
            func && func();
        }
    }

    /**
     * no:02
     * 上传控件
     * author:陈偲
     * time:20161202
     * author:申立新
     * update:20170109
     */
    function uploadControl(inputObj, imgObj, hidObj) {
        var $input = $(inputObj);
        var $result = $(imgObj);
        var $hid = $(hidObj);

        var imgData;

        $input.on('change', function () {
            var $this = $(this);
            var file = this.files[0];

            var id = $this.data('id');

            if (!file) {
                return;
            }

            if (!/image\/\w+/.test(file.type)) {
                alert("只支持上传图片");
                return false;
            }

            if (file.size / 1024 > o.fileSize) {
                Common.toast('您要上传的身份证照片太大了~', 4500);

                return false;
            }

            var w = 89;
            var h = 75;
            var originalScale = w / h; //原图宽高比

            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                var imgDataOriginal = this.result;

                var img = new Image;

                quality = 1, //image quality
                    canvas = document.createElement("canvas");
                drawer = canvas.getContext("2d");
                img.src = imgDataOriginal;
                img.onload = function () {
                    var thisObj = this;

                    var width = img.width;
                    var height = img.height;

                    var whScale = width / height; //显示宽高比

                    var actualHeight = 0;
                    var actualWidth = 0;
                    if (width < w && height < h) {

                        actualWidth = width;

                        actualHeight = height;

                    } else {

                        if (whScale <= originalScale) {
                            actualWidth = width * (h / height);

                            actualHeight = h;


                        } else {

                            actualHeight = height * (w / width);

                            actualWidth = w;

                        };
                    };
                    canvas.width = actualWidth;
                    canvas.height = actualHeight;

                    // canvas.width = thisObj.width;
                    // canvas.height = thisObj.height;
                    // drawer.drawImage(thisObj, 0, 0);
                    drawer.drawImage(thisObj, 0, 0, canvas.width, canvas.height);
                    imgData = canvas.toDataURL("image/jpeg", quality);
                    // console.log(imgData);
                    $result.attr('src', imgData);
                    $result.css("opacity", "1");

                    // *******************************************************
                    // $hid.val(imgDataOriginal);

                    uploadImg(imgDataOriginal, id);
                }
            }
        });
    }

    // 上传图片
    function uploadImg(data, id) {
        var data = {
            p: data,
            id: id
        }

        var url = createServerUrl('uploadImg');

        Common.preloader.show('图片上传中...');

        Common.AjaxPostData(url, data, function (r) {
            if (r.code == 0) {
                // 上传成功
                var result = r.msg;

                $('#p' + result.id).val(result.file);

                Common.toast('上传成功', 5000);
            } else {
                // 上传失败，请重新上传
            }
        }, function() {
            Common.toast('因网络原因，图片上传失败，请重新选择图片~', 5000);
        }, function () {
            Common.preloader.hide();
        });
    }

    //获取验证码的按钮点击
    function getCodeClick() {
        $('#btn_get_code').one('click', function () {
            var obj = $(this);
            var phoneNum = $('#tel').val();

            if (!(phoneNum.Trim())) {
                Common.toast('请输入手机号', 2400);
                getCodeClick();
            } else if (phoneNum.IsPhone()) {
                var url = createServerUrl('getCode');
                var data = {
                    tel: phoneNum
                };

                Common.AjaxGetData(url, data, function (r) {
                    if (r.code == 0) {
                        Common.toast('验证码已发送，请查收', 2400);
                    } else if (r.code == 1) {
                        Common.toast('该手机已登记', 2400);
                    } else if (r.code == 2) {
                        Common.toast('您点的太快了，慢点~', 2400);
                    } else {
                        Common.toast('验证码发送失败！', 2400);
                    }
                });

                var text1 = obj.html();
                var seconds = 60;
                var interval = setInterval(function () {

                    var text = seconds + '秒';

                    obj.html(text);

                    if (seconds === -1) {
                        obj.html(text1);
                        clearInterval(interval);
                        getCodeClick();
                    }

                    --seconds;
                }, 999);
            } else {
                alert('请输入正确的手机号!');
                getCodeClick();
            }
        });
    }

    function submit() {
        var pwd = $('#pwd').val().Trim();
        var confirmPwd = $('#confirm_pwd').val().Trim();

        if (pwd != confirmPwd) {
            Common.toast('您两次输入的密码不一致', 5000);

            return false;
        }

        var verArr = [
            '#name', '#id_card', '#pwd', '#p1', '#p2', '#tel', '#code'
        ];

        if ($('#referrer').val().Trim()) {
            verArr.push('#referrer')
        }

        var result = Common.verificationControlVal(verArr);

        if (result) {
            return false;
        }

        if (!$('#agree_about')[0].checked) {
            Common.toast('请确认已同意并已阅读《风险揭示书》', 5000);

            return false;
        }

        var data = $('#frm').serializeObject();

        // var url = createServerUrl('save1');
        var url = createServerUrl('save');

        Common.preloader.show();

        Common.AjaxPostData(url, data, function (r) {
            if (r.code == 0) {  //成功
                Common.toast('登记成功', 5000);
                setTimeout(function () {
                    $('.shadow,#dialog_result').fadeIn(200);
                }, 1500);
            } else if (r.code == 1) {   //用户已存在
                Common.toast('您登记的用户已存在', 5000);
            } else if (r.code == 2) {   //验证码不正确
                Common.toast('验证码不正确', 5000);
            } else {    //未知错误
                Common.toast('您登记没有成功', 5000);
            }
        }, null, function () {
            Common.preloader.hide();
        });
    }

    $(function () {
        o = setParam();

        initPage();
    });
})();